package org.geektimes.projects.user.message;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/4/2 15:21
 */
public class MessageProducerFactory implements ObjectFactory {


    private String queueName = "TEST.FOO";

    private String connecitonFactoryJndiName = "jms/activemq-factory";



    @Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
        ConnectionFactory connectionFactory = (ConnectionFactory)nameCtx.lookup(connecitonFactoryJndiName);
        //通过 工厂 创建 连接
        Connection connection = connectionFactory.createConnection();
        connection.start();

        //通过连接创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建监听队列
        Destination destination = session.createQueue(queueName);

        //创建生产者
        MessageProducer producer = session.createProducer(destination);

        return producer;
    }



    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public void setConnecitonFactoryJndiName(String connecitonFactoryJndiName) {
        this.connecitonFactoryJndiName = connecitonFactoryJndiName;
    }
}
